package controllers

import (
	"github.com/gin-gonic/gin"
	"local/services"
	"strconv"
)

//登录示例
func Login(c *gin.Context) {

	username := c.Query("username")
	password := c.Query("password")

	token, ok := services.Login(username, password)

	if ok {
		c.JSON(200, gin.H{"code": 200, "msg": "登录成功", "data": token})
	} else {
		c.JSON(400, gin.H{"code": 400, "msg": "操作失败"})
	}
	return
}

//增删改查示例
func SelectUserById(c *gin.Context) {

	id := c.Query("id")
	int64_id, _ := strconv.ParseInt(id, 10, 64)

	res, err := services.SelectUserByIdService(int64_id)

	if err != nil {
		c.JSON(400, gin.H{"code": 400, "msg": "操作失败", "data": err})
	} else {
		c.JSON(200, gin.H{"code": 200, "msg": "操作成功", "data": res})
	}
	return
}

func UpdateUserById(c *gin.Context) {

	id := c.Query("id")
	int64_id, _ := strconv.ParseInt(id, 10, 64)

	name := c.Query("name")

	status := c.Query("status")
	int64_status, _ := strconv.ParseInt(status, 10, 64)

	res, err := services.UpdateUserByIdService(int64_id, name, int64_status)

	if err != nil {
		c.JSON(400, gin.H{"code": 400, "msg": "操作失败", "data": err})
	} else {
		c.JSON(200, gin.H{"code": 200, "msg": "操作成功", "data": res})
	}
	return
}

func DeleteUserById(c *gin.Context) {

	id := c.Query("id")
	int64_id, _ := strconv.ParseInt(id, 10, 64)

	res, err := services.DeleteUserByIdService(int64_id)

	if err != nil {
		c.JSON(400, gin.H{"code": 400, "msg": "操作失败", "data": err})
	} else {
		c.JSON(200, gin.H{"code": 200, "msg": "操作成功", "data": res})
	}
	return
}

func InsertUser(c *gin.Context) {

	name := c.Query("name")

	res, err := services.InsertUserService(name)

	if err != nil {
		c.JSON(400, gin.H{"code": 400, "msg": "操作失败", "data": err})
	} else {
		c.JSON(200, gin.H{"code": 200, "msg": "操作成功", "data": res})
	}
	return
}
